import { Injectable,Req } from '@nestjs/common';
import { UserService} from "../user/user.service";
import { JwtService } from '@nestjs/jwt';

@Injectable()
export class AuthService {
    constructor(
        private readonly userService:UserService,
        private readonly jwtService: JwtService
    ){}
    async validateUser(username: string, pass: string): Promise<any> {
        const user = await this.userService.findOne(username);
        if (user && user.password === pass) {
            const { password, ...result } = user;
            return result;
        }
        return null;
    }

    /**
     * 登陆后获取密钥加密的jwt，前端请求需要后面请求头部带上Authorization: Beaer JwtToken
     * @param user
     */
    async login(user: any) {
        const payload = { username: user.username, id: user._id };
        return {
            access_token: this.jwtService.sign(payload),
        };
    }

}
